package org.gameg.Api.Service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.models.auth.In;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.gameg.Api.Service.ApiService;
import org.gameg.Api.entity.SysUserOperate;
import org.gameg.bean.Player;
import org.gameg.bean.Power;
import org.gameg.mapper.biz.*;
import org.gameg.model.biz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class ApiServiceImpl implements ApiService {

    @Autowired
    private TPlayerMapper tPlayerMapper;
    @Autowired
    private TokenMapper tokenMapper;
    @Autowired
    private TGameMapper tGameMapper;
    @Autowired
    private TGamePowerMapper tGamePowerMapper;
    @Autowired
    private TGameUserMapper tGameUserMapper;
    @Autowired
    private TOrderMapper tOrderMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TGamePlayerMapper tGamePlayerMapper;
    @Autowired
    private TDrawMapper tDrawMapper;
    @Autowired
    private TJackpotMapper tJackpotMapper;
    @Autowired
    private TConditionMapper tConditionMapper;
    @Autowired
    private TRebateMapper tRebateMapper;


    /**
     * 情况：1.用户第一次授权
     * 2.用户使用已授权的激活码在其他设备上面授权
     * 逻辑1:在授权时核对授权码是否可用，是否可以授权的话添加用户。并添加授权码。
     * 逻辑2:授权时核对授权码是否已过期，密码是否正确。
     *
     * @param player 用户信息
     * @param token  授权码信息
     * @return true 成功； false 失败（授权码错误）
     */
    @Override
    public Object authorization(TPlayer player, Token token) {
        //System.out.println(tokenMapper.selectList(new EntityWrapper<>()));
        Object result = new Object();
        //寻找该用户是否拥有token
        TPlayer param = new TPlayer();
        param.setPlaye_token(token.getPlayerToken());
        param.setPassword(player.getPassword());
        TPlayer player1 = tPlayerMapper.selectOne(param);
        if (player1 != null) {//之前已经绑定过token 校验密码,并且该用户密码校验通过
            //更新Player 和 token
            String sysToken = getToken(token.getPhoneNumber() + player.getPassword(), token.getPlayerToken());
            player.setPlaye_token(player1.getPlaye_token());
            player.setId(player1.getId());
            player.setToken(sysToken);
            Token tokenParam = new Token();
            tokenParam.setPlayerToken(token.getPlayerToken());
            Token token1 = tokenMapper.selectByToken(tokenParam);

            if (token1 != null && token1.getStatus() != null && token1.getStatus().equals(1)) {
                token1.setToken(sysToken);
                token1.setPhoneNumber(token.getPhoneNumber());
                token1.setPhoneType(token.getPhoneType());
                tokenMapper.updateById(token1);
                tPlayerMapper.updateById(player);
                result = sysToken;
            } else {
                result = null;
            }
        } else {
            //token 中的token不能为空。 通过token去寻找token码
            Token tokenParam = new Token();
            tokenParam.setPlayerToken(token.getPlayerToken());
            //Token token1 = tokenMapper.selectByToken(tokenParam);
            Token token1 = tokenMapper.selectOne(tokenParam);
            if (token1 != null) {//找到了,可以激活
                String sysToken = getToken(token.getPhoneNumber()+player.getPassword(),token.getPlayerToken());
                player.setPlaye_token(token.getPlayerToken());
                player.setToken(sysToken);
                token1.setToken(sysToken);
                token1.setStatus(1);
                token1.setActivateDate(new Date());
                token1.setEndDate(getEndDate(token1.getValidity()));
                token1.setPhoneType(token.getPhoneType());
                token1.setPhoneNumber(token.getPhoneNumber());
                tokenMapper.updateById(token1);
                tPlayerMapper.insert(player);
                result = sysToken;
            } else {
                result = null;
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> saveGame(TGame tGame) {
        Map<String, Object> res = new HashMap<>();
        //tGame 中 token 必须传递。
        if (tGame.getToken() == null || tGame.equals("")) {
            res.put("msg", "用户已失效");
            res.put("code", false);
        } else {//有token 校验token是否合法
            TPlayer tPlayer = new TPlayer();
            tPlayer.setToken(tGame.getToken());
            Token token = new Token();
            token.setToken(tGame.getToken());
            token.setStatus(1);//状态：激活
            token = tokenMapper.selectOne(token);
            tPlayer = tPlayerMapper.selectOne(tPlayer);
            if (token == null||tPlayer == null) {
                res.put("msg", "api_token无效");
                res.put("code", false);
            } else { //为有效token  1.有该token的游戏设置，直接修改，否则，添加
                TGame param = new TGame();
                param.setPlayer_token(token.getPlayerToken());
                TGame game = tGameMapper.selectOne(tGame);
                if (game != null) {//该设备已经设置过游戏规则
                    tGame.setId(game.getId());
                    tGame.setUpdateTime(new Date());
                    tGameMapper.updateById(tGame);
                    TGamePower power1 = new TGamePower();
                    power1.setPowerToken(tGame.getPlayer_token());
                    EntityWrapper<TGamePower> powerEntityWrapper = new EntityWrapper<>();
                    powerEntityWrapper.where("power_token={0}", power1.getPowerToken());
                    tGamePowerMapper.delete(powerEntityWrapper);
                    for (TGamePower power :
                            tGame.getPowers()) {
                        //删除后添加
                        power.setPowerToken(tGame.getPlayer_token());
                        power.setGameId(tGame.getId());
                        tGamePowerMapper.insert(power);
                    }
                } else {//没有设置过游戏规则
                    tGame.setUpdateTime(new Date());
                    tGame.setCreateTime(new Date());
                    tGameMapper.insert(tGame);
                    for (TGamePower power :
                            tGame.getPowers()) {
                        power.setPowerToken(tGame.getPlayer_token());
                        power.setGameId(tGame.getId());
                        tGamePowerMapper.insert(power);
                    }
                }
                res.put("msg", "设置成功");
                res.put("code", true);
            }
        }
        return res;
    }

    @Override
    public Map<String, Object> saveIntegral(TPlayer player, TGameUser gameUser) {
        Map<String, Object> map = new HashMap<>();
        TPlayer param = new TPlayer();
        param.setToken(player.getToken());
        TPlayer tPlayer = tPlayerMapper.selectOne(param);
        if (tPlayer == null) {//没有改用户
            map.put("msg", "用户已失效");
            map.put("code", 200);
        } else {
            TGameUser tParam = new TGameUser();
            tParam.setTplayerId(tPlayer.getId());
            tParam.setGamePlayerId(gameUser.getGamePlayerId());
            TGameUser tGameUser = tGameUserMapper.selectOne(tParam);
            TOrder tOrder = new TOrder();
            tOrder.setGameUserId(tGameUser.getGamePlayerId());
            tOrder.setPlayerId(tGameUser.getTplayerId());
            tOrder.setScore(gameUser.getSaveScore());
            tOrder.setType(gameUser.getType());
            switch (gameUser.getType()) {
                case 1://上分
                    gameUser.setCreditScore(tGameUser.getCreditScore() + gameUser.getSaveScore());
                    tOrder.setCreditScore(tGameUser.getCreditScore() + gameUser.getSaveScore());
                    break;
                case 2://下分
                    gameUser.setCreditScore(tGameUser.getCreditScore() + gameUser.getSaveScore());
                    tOrder.setCreditScore(tGameUser.getCreditScore() + gameUser.getSaveScore());
                    break;
                case 3://上庄
                    gameUser.setZjScore(-gameUser.getSaveScore());
                    gameUser.setCreditScore(tGameUser.getCreditScore() + gameUser.getSaveScore());
                    tOrder.setCreditScore(tGameUser.getCreditScore() + gameUser.getSaveScore());
                    break;
                case 4://下庄
                    gameUser.setZjScore(0);
                    gameUser.setCreditScore(tGameUser.getCreditScore() + gameUser.getZjScore());
                    tOrder.setCreditScore(tGameUser.getCreditScore() + gameUser.getZjScore());
                    break;
            }
            gameUser.setTplayerId(tPlayer.getId());
            gameUser.setUpdateTime(new Date());
            gameUser.setUpdateBy(tPlayer.getId());
            tGameUserMapper.update(gameUser, new EntityWrapper<TGameUser>().where("game_player_id={0}", gameUser.getGamePlayerId()));
            tOrderMapper.insert(tOrder);
            map.put("msg", "设置成功");
            map.put("code", 200);
            map.put("data", gameUser);
        }
        return map;
    }

    @Override
    public Map<String, Object> createGameUser(TGameUser gameUser,String token) {
        Map<String, Object> map = new HashMap<>();
        TPlayer params = new TPlayer();
        params.setToken(token);
        TPlayer tPlayer = tPlayerMapper.selectOne(params);
        if (tPlayer == null) {
            map.put("msg", "用户已失效");
            map.put("code", 200);
        } else {
            //校验是否换群，或者 用户id是否
            TGameUser param = new TGameUser();
            param.setGamePlayerId(Long.valueOf(tPlayer.getPhone()));
            TGameUser tGameUser = tGameUserMapper.selectOne(param);
            gameUser.setCreateTime(new Date());
            gameUser.setCreateBy(gameUser.getGamePlayerId());
            gameUser.setUpdateBy(gameUser.getGamePlayerId());
            gameUser.setUpdateTime(new Date());
            if (tGameUser != null) {
                gameUser.setId(tGameUser.getId());
                tGameUserMapper.updateById(gameUser);
                map.put("msg", "玩家已存在，玩家信息已更新");
                map.put("code", 200);
                map.put("isSuccess", true);
            } else {
                gameUser.setCreateTime(new Date());
                gameUser.setCreateBy(gameUser.getGamePlayerId());
                gameUser.setUpdateBy(gameUser.getGamePlayerId());
                gameUser.setUpdateTime(new Date());
                gameUser.setSaveScore(0);
                gameUser.setZjScore(0);
                gameUser.setCreditScore(0);
                int i = tGameUserMapper.insert(gameUser);
                if (i == 0) {
                    map.put("msg", "玩家创建失败，请手动创建");
                    map.put("code", 200);
                    map.put("isSuccess", false);
                } else {
                    map.put("msg", "玩家创建成功");
                    map.put("code", 200);
                    map.put("isSuccess", true);
                }
            }
        }
        return map;
    }

    @Override
    public Page<Token> getTokenPage(Page<Token> page, Token token) {
        Wrapper<Token> wrapper = new EntityWrapper<>();
        ((EntityWrapper<Token>) wrapper).setEntity(token);
        List<Token> pageList = tokenMapper.selectPage(page, wrapper);
        for (Token t :
                pageList) {
            if (t.getUserId() != null) {
                SysUser user = sysUserMapper.selectById(t.getUserId());
                if (user != null) {
                    t.setUserName(user.getAccount());
                }
            }
            TPlayer param = new TPlayer();
            param.setPlaye_token(t.getPlayerToken());
            TPlayer player = tPlayerMapper.selectOne(param);
            if (player != null) {
                t.setPhone(player.getPhone());
            }
        }
        page.setRecords(pageList);
        return page;
    }

    @Override
    public Object addOrUpDateToken(Token token) {
        Map<String, Object> map = new HashMap<>();
        if (token != null && token.getId() != null) {//拉黑，拉白
            if (token.getStatus().equals(3)) {
                token.setBlockTime(new Date());
            } else {
                token.setWhiteTime(new Date());
            }
            token.setUpdateTime(new Date());
            tokenMapper.updateById(token);
            map.put("code", 200);
            if (token.getStatus().equals(3)) {
                map.put("msg", "拉黑成功");
            } else {
                map.put("msg", "拉白成功");
            }
            map.put("isSuccess", true);
        } else if (token != null && token.getId() == null) {
            if (token.getTokenSize() > 0) {
                for (int i = 0; i < token.getTokenSize(); i++) {
                    Token token1 = new Token();
                    token1.setUserId(SysUserOperate.getUser().getId());
                    token1.setStatus(0);
                    token1.setPlayerToken(getPlayerToken());
                    token1.setCreateDate(new Date());
                    token1.setCreateTime(new Date());
                    token1.setCreateBy(token.getUserId());
                    token1.setUpdateTime(new Date());
                    token1.setUpdateBy(token.getUserId());
                    token1.setUnit(token.getUnit());
                    token1.setValidity(token.getValidity());
                    tokenMapper.insert(token1);
                }
            }
            map.put("code", 200);
            map.put("msg", "添加成功");
            map.put("isSuccess", true);
        } else {
            map.put("code", 200);
            map.put("msg", "提交表单为空");
            map.put("isSuccess", false);
        }
        return map;
    }

    @Override
    public Map<String, Object> insert(SysUser user) {
        SysUser user1 = SysUserOperate.getUser();
        Map<String, Object> map = new HashMap<>();
        if (!user1.getUserName().equals("admin")) {
            map.put("mag", "非管理员不允许添加用户");
            map.put("code", 200);
            map.put("isSuccess", false);
            return map;
        }
        if (user.getId() != null) {//修改
            try {
                user.setUpdateBy(SysUserOperate.getUser().getId());
                user.setUpdateTime(new Date());
                sysUserMapper.updateById(user);
                map.put("mag", "修改用户信息成功");
                map.put("code", 200);
                map.put("isSuccess", true);
            } catch (Exception e) {
                map.put("mag", "修改用户信息失败");
                map.put("code", 200);
                map.put("isSuccess", false);
            }
        } else {//添加
            try {
                SysUser param = new SysUser();
                param.setUserName(user.getUserName());
                SysUser sysUser = sysUserMapper.selectOne(param);
                if (sysUser != null) {
                    map.put("mag", "用户已存在");
                    map.put("code", 200);
                    map.put("isSuccess", false);
                    return map;
                }
                long userId = SysUserOperate.getUser().getId();
                user.setUpdateTime(new Date());
                user.setCreateTime(new Date());
                user.setCreateBy(userId);
                user.setUpdateBy(userId);
                sysUserMapper.insert(user);
                map.put("mag", "添加用户信息成功");
                map.put("code", 200);
                map.put("isSuccess", true);
            } catch (Exception e) {
                map.put("mag", "添加用户信息失败");
                map.put("code", 200);
                map.put("isSuccess", false);
            }
        }
        return map;
    }

    @Override
    public Page<TGamePlayer> getGamePlayStatistics(Page<TGamePlayer> page, TPlayer tPlayer) {
        List<TGamePlayer> tGamePlayerList =tGamePlayerMapper.getGamePlayStatistics(page,tPlayer);
        page.setRecords(tGamePlayerList);
        return page;
    }

    @Override
    public Map<String, Object> getGamePlayerDetail(Long playerId, Page<TGamePlayer> pageGame, Page<TOrder> pageOrder) {
        Map<String, Object> map = new HashMap<>();
        List<TGamePlayer> tGamePlayerList = tGamePlayerMapper.selectPage(pageGame, new EntityWrapper<TGamePlayer>().where("player_id={0}",playerId));
        List<TOrder> tOrderList = tOrderMapper.selectPage(pageOrder, new EntityWrapper<TOrder>().where("player_id={0}",playerId));
        map.put("gamePlayer", tGamePlayerList);
        map.put("code", 200);
        return map;
    }

    @Override
    public Map<String, Object> getOrderDetail(Long playerId, Page<TOrder> pageOrder) {
        Map<String, Object> map = new HashMap<>();
        List<TOrder> tOrderList = tOrderMapper.selectPage(pageOrder, new EntityWrapper<TOrder>().where("player_id={0}",playerId));
        map.put("order", tOrderList);
        map.put("code", 200);
        return map;
    }

    @Override
    public Map<String, Object> getDrawStatistics(Long playerId,String token) {
        Map<String, Object> map = new HashMap<>();
        boolean res = verify(token);
        if (!res) {
            map.put("msg", "用户已失效");
            map.put("code", 200);
        } else {
            List<TDraw> tDrawList = new ArrayList<>();
            TDraw tDraw = tDrawMapper.selectTDrawList(playerId);
            TDraw tDraw1 = tDrawMapper.selectQb(playerId);
            if (tDraw1 != null) {
                tDraw.setQb(tDraw1.getQb());
            }
            tDrawList = tDrawMapper.selectList(new EntityWrapper<TDraw>().eq("player_id", playerId));
            map.put("statistics", tDraw);
            map.put("tdrawDetail", tDrawList);
            map.put("code", 200);
        }
        return map;
    }

    @Override
    public Object addOrUpdateJackpot(TJackpot tJackpot, String token) {
        Map<String, Object> map = new HashMap<>();
        //先校验token的有效性
        boolean res = verify(token);
        if (!res) {
            map.put("msg", "用户已失效");
            map.put("code", 200);
        } else {//走业务。
            if (tJackpot.getId() != null) {//修改
                tJackpot.setUpdateTime(new Date());
                tJackpot.setUpdateBy(tJackpot.getPlayerId());
                tJackpotMapper.updateById(tJackpot);
                map.put("msg", "设置成功！");
                map.put("code", 200);
            } else {//添加
                tJackpot.setCreateTime(new Date());
                tJackpot.setCreateBy(tJackpot.getPlayerId());
                tJackpotMapper.insert(tJackpot);
                map.put("msg", "设置成功！");
                map.put("code", 200);
            }

        }
        return map;
    }

    @Override
    public Object getJackpot(TJackpot tJackpot, String token) {
        Map<String, Object> map = new HashMap<>();
        //先校验token的有效性
        boolean res = verify(token);
        if (!res) {
            map.put("msg", "用户已失效");
            map.put("code", 200);
        } else {//走业务。
            TJackpot tJackpot1 = tJackpotMapper.selectOne(tJackpot);
            map.put("msg", "获取配置信息成功");
            map.put("data", tJackpot1);
            map.put("code", 200);
        }
        return map;
    }

    @Override
    public Object addOrUpdateCondition(TCondition tCondition, String token) {
        Map<String, Object> map = new HashMap<>();
        //先校验token的有效性
        boolean res = verify(token);
        if (!res) {
            map.put("msg", "用户已失效");
            map.put("code", 200);
        } else {//走业务。
            if (tCondition.getId() != null) {//修改
                tCondition.setUpdateTime(new Date());
                tCondition.setUpdateBy(tCondition.getPlayerId());
                tConditionMapper.updateById(tCondition);
                map.put("msg", "设置成功！");
                map.put("code", 200);
            } else {//添加
                tCondition.setCreateTime(new Date());
                tCondition.setCreateBy(tCondition.getPlayerId());
                tConditionMapper.insert(tCondition);
                map.put("msg", "设置成功！");
                map.put("code", 200);
            }
        }
        return map;
    }

    @Override
    public Object getCondition(TCondition condition, String token) {
        Map<String, Object> map = new HashMap<>();
        //先校验token的有效性
        boolean res = verify(token);
        if (!res) {
            map.put("msg", "用户已失效");
            map.put("code", 200);
        } else {//走业务。
            List<TCondition> conditionList = tConditionMapper.selectList(new EntityWrapper<TCondition>().where("player_id={0}",condition.getPlayerId()));
            map.put("msg", "获取配置信息成功");
            map.put("data", conditionList);
            map.put("code", 200);
        }
        return map;
    }

    @Override
    public Object addOrUpdateRebate(TRebate rebate, String token) {
        Map<String, Object> map = new HashMap<>();
        //先校验token的有效性
        boolean res = verify(token);
        if (!res) {
            map.put("msg", "用户已失效");
            map.put("code", 200);
        } else {//走业务。
            if (rebate.getId() != null) {//修改
                rebate.setUpdateTime(new Date());
                rebate.setUpdateBy(rebate.getPlayerId());
                tRebateMapper.updateById(rebate);
                map.put("msg", "设置成功！");
                map.put("code", 200);
            } else {//添加
                rebate.setCreateTime(new Date());
                rebate.setCreateBy(rebate.getPlayerId());
                tRebateMapper.insert(rebate);
                map.put("msg", "设置成功！");
                map.put("code", 200);
            }
        }
        return map;
    }

    @Override
    public Object getRebate(TRebate rebate, String token) {
        Map<String, Object> map = new HashMap<>();
        //先校验token的有效性
        boolean res = verify(token);
        if (!res) {
            map.put("msg", "用户已失效");
            map.put("code", 200);
        } else {//走业务。
            List<TRebate> rebateList = tRebateMapper.selectList(new EntityWrapper<TRebate>().where("player_id={0}",rebate.getPlayerId()));
            map.put("msg", "获取配置信息成功");
            map.put("data", rebateList);
            map.put("code", 200);
        }
        return map;
    }

    @Override
    public void rebate() {
        //获取用户信息；
        List<TPlayer> playerList = tPlayerMapper.selectList(new EntityWrapper<>());
        //判断playerList是否为空 。不为空继续逻辑,避免空指针。
        if (playerList != null && playerList.size() > 0) {
            //初始化数据
            for (TPlayer player :
                    playerList) {
                //获取反水规则；
                List<TRebate> rebateList = tRebateMapper.selectList(new EntityWrapper<TRebate>()
                        .where("player_id={0}",player.getPhone()).orderBy("start_rebate",true));
                //获取游戏玩家
                List<TGameUser> tGameUserList = tGameUserMapper.selectList(new EntityWrapper<TGameUser>()
                        .where("tplayer_id", player.getPhone()));
                //遍历用户获取用户当天比赛记录
                for (TGameUser user :
                        tGameUserList) {
                    List<TGamePlayer> gamePlayerList = tGamePlayerMapper.selectList(new EntityWrapper<TGamePlayer>()
                            .where("game_user_id={0}", user.getId())
                            .between("create_time",getDate(-1),getDate(0)));
                    Integer betSum = 0;
                    //遍历gamePlayerList 汇总总押注数
                    for (TGamePlayer gamePlayer :
                            gamePlayerList) {
                        if (gamePlayer.getBet() != null) {
                            betSum += gamePlayer.getBet();
                        }
                    }
                    TOrder tOrder = null;
                    for (TRebate rebate :
                            rebateList) {
                        //判断rebate.getEndRebate()不能为空，存在为空的情况
                        if (rebate.getEndRebate() != null && rebate.getEndRebate() != 0) {
                            if (betSum >= rebate.getStartRebate() && betSum <= rebate.getEndRebate()) {//符合该反水条件
                                tOrder = new TOrder();
                                //计算反水
                                Double rebatePrice = betSum * rebate.getPrice().doubleValue() / 100;
                                //修改反水金额
                                user.setCreditScore((int) (user.getCreditScore() + rebatePrice));
                                tOrder.setGameUserId(user.getId());
                                tOrder.setScore(rebatePrice.intValue());
                                tOrder.setCreditScore(user.getCreditScore());
                                tOrder.setType(5);//5：反水类型为5
                                tOrder.setPlayerId(Integer.valueOf(player.getPhone()));
                            } else {
                                continue;
                            }
                        } else {
                            if (betSum >= rebate.getStartRebate()) {
                                tOrder = new TOrder();
                                //计算反水
                                Double rebatePrice = betSum * rebate.getPrice().doubleValue() / 100;
                                //修改反水金额
                                user.setCreditScore((int) (user.getCreditScore() + rebatePrice));
                                tOrder.setGameUserId(user.getId());
                                tOrder.setScore(rebatePrice.intValue());
                                tOrder.setCreditScore(user.getCreditScore());
                                tOrder.setType(5);//5：反水类型为5
                                tOrder.setPlayerId(Integer.valueOf(player.getPhone()));
                            } else {
                                continue;
                            }
                        }
                        break;
                    }
                    //修改用户，添加订单
                    if (tOrder != null) {
                        tOrder.setCreateTime(new Date());
                        tGameUserMapper.updateById(user);
                        tOrderMapper.insert(tOrder);
                    }
                }
            }
        }

    }

    @Override
    public void giveAword() {
        //获取用户信息；
        List<TPlayer> playerList = tPlayerMapper.selectList(new EntityWrapper<>());
        if (playerList != null && playerList.size() > 0) {
            for (TPlayer player :
                    playerList) {
                TJackpot param = new TJackpot();
                param.setPlayerId(Long.valueOf(player.getPhone()));
                TJackpot jackpot = tJackpotMapper.selectOne(param);
                //获取奖励条件
                List<TCondition> tConditions = tConditionMapper.selectList(new EntityWrapper<TCondition>()
                        .where("jackpot_id={0}", jackpot.getId())
                        .eq("type", "1")
                        .orderBy("type")
                        .orderBy("award_condition"));
                if (tConditions != null && tConditions.size() > 0) {//不为空，可以继续
                    TCondition condition = tConditions.get(0);
                    if (condition.getGiveTime().getTime() < new Date().getTime()) { // 时间超过执行任务时间,可执行
                        //condition执行条件验证，发放奖励。
                        //获取游戏玩家
                        List<TGameUser> tGameUserList = tGameUserMapper.selectList(new EntityWrapper<TGameUser>()
                                .where("tplayer_id", player.getPhone()).orderBy("create_time"));
                        for (TGameUser user :
                                tGameUserList) {
                            List<TGamePlayer> gamePlayerList = tGamePlayerMapper.selectList(new EntityWrapper<TGamePlayer>()
                                    .where("game_user_id={0}", user.getId())
                                    .between("create_time",getDate(-1),getDate(0)));
                            Integer betSum = 0;
                            //遍历gamePlayerList 汇总总押注数
                            for (TGamePlayer gamePlayer :
                                    gamePlayerList) {
                                if (gamePlayer.getBet() != null) {
                                    betSum += gamePlayer.getBet();
                                }
                            }
                            //平均押注
                            Integer avgBet = betSum / gamePlayerList.size();
                            TOrder tOrder = null;
                            int i = 0;
                            for (TCondition con:
                                 tConditions) {
                                i++;
                                if (con.getType().equals("1")) {//次数奖励
                                    if (i > tConditions.size() - 1) {
                                        if (tGameUserList.size() > Integer.valueOf(con.getAwardCondition())
                                                && tGameUserList.size() < Integer.valueOf(tConditions.get(i).getAwardCondition())) {
                                            tOrder = new TOrder();
                                            //刚好在比这个局数范围大。
                                            //确定发奖金额比例。按照发奖比例发奖

                                            //end
                                            //发奖，暂时按照全比例发奖
                                            user.setCreditScore(user.getCreditScore() + (int) con.getPrice().doubleValue());
                                            tOrder.setGameUserId(user.getId());
                                            tOrder.setScore((int) con.getPrice().doubleValue());
                                            tOrder.setCreditScore(user.getCreditScore());
                                            tOrder.setType(6);//6：奖池次数奖励
                                            tOrder.setPlayerId(Integer.valueOf(player.getPhone()));
                                        } else {
                                            continue;
                                        }
                                    } else {
                                        if (tGameUserList.size() > Integer.valueOf(con.getAwardCondition())) {
                                            tOrder = new TOrder();
                                            //刚好在比这个局数范围大。
                                            //确定发奖金额比例。按照发奖比例发奖

                                            //end
                                            //发奖，暂时按照全比例发奖
                                            user.setCreditScore(user.getCreditScore() + (int) con.getPrice().doubleValue());
                                            tOrder.setGameUserId(user.getId());
                                            tOrder.setScore((int) con.getPrice().doubleValue());
                                            tOrder.setCreditScore(user.getCreditScore());
                                            tOrder.setType(6);//6：奖池次数奖励
                                            tOrder.setPlayerId(Integer.valueOf(player.getPhone()));
                                        } else {
                                            continue;
                                        }
                                    }
                                    break;
                                }
                            }
                            //修改用户，添加订单。（如果订单不为空的情况下）
                            if (tOrder != null) {
                                tGameUserMapper.updateById(user);
                                tOrderMapper.insert(tOrder);
                                jackpot = tJackpotMapper.selectOne(param);
                                jackpot.setPrice(BigDecimal.valueOf(jackpot.getPrice().doubleValue()-tOrder.getScore()));
                                tJackpotMapper.updateById(jackpot);
                            }
                        }
                    } else {
                        return;
                    }
                }
            }
        }
    }

    @Override
    public void aword(Player p) {
        //获取用户
        TGameUser user = tGameUserMapper.selectById(p.getId());
        if (user != null) {
            TJackpot param = new TJackpot();
            param.setPlayerId(p.getPlayerId());
            TJackpot jackpot = tJackpotMapper.selectOne(param);
            //通过奖池id去获取获奖规则。
            List<TCondition> conditions = tConditionMapper.selectList(new EntityWrapper<TCondition>()
                    .where("jackpot_id={0}", jackpot.getId())
                    .eq("player_id", p.getPlayerId())
                    .notIn("type", "1")
                    .orderBy("type")
                    .orderBy("award_condition"));
            List<TGamePlayer> gamePlayerList = tGamePlayerMapper.selectList(new EntityWrapper<TGamePlayer>()
                    .where("game_user_id={0}", user.getId())
                    .orderBy("create_time", false)
            );
            Integer betSum = betSum(gamePlayerList);
            Integer lianWin = getLianWin(gamePlayerList);
            //遍历gamePlayerList 汇总总押注数
            //平均押注
            Integer avgBet = betSum / gamePlayerList.size();
            TOrder tOrder = null;
            double aword = 0;
            for (TCondition condition :
                    conditions) {
                String type = condition.getType();
                if (type.equals("2")) {//连胜奖励
                    //确定连胜奖励范围
                    if (condition.getAwardCondition().equals(lianWin)) {
                        //确定后发放奖励
                        aword = condition.getPrice().doubleValue();
                        //确定发奖金额比例。按照发奖比例发奖

                        //end
                        //发奖，暂时按照全比例发奖
                        user.setCreditScore(user.getCreditScore() + (int) aword);
                        while (true) {
                            jackpot = tJackpotMapper.selectOne(param);
                            if (jackpot.getPrice().doubleValue() - tOrder.getScore() > 0) {
                                jackpot.setPrice(BigDecimal.valueOf(jackpot.getPrice().doubleValue() - tOrder.getScore()));
                            } else {
                                aword = jackpot.getPrice().doubleValue();
                                jackpot.setPrice(BigDecimal.valueOf(0));
                            }
                            tOrder = gatOrder(user.getId(), (int) aword, user.getCreditScore(), 7, p.getPlayerId());
                            int success = tJackpotMapper.updateById(jackpot);
                            if (success > 0) {
                                break;
                            }
                        }
                        tGameUserMapper.updateById(user);
                        tOrderMapper.insert(tOrder);
                    } else {
                        continue;
                    }
                } else if (type.equals("3")) {//数字奖励                 //暂时有bug
                    double []number = getNum(condition.getAwardCondition());
                    int point = p.getPoint();
                    for (int i = 0; i < number.length; i++) {
                        if (point == number[i]) {
                            //发奖
                            aword = condition.getPrice().doubleValue();
                            //确定发奖金额比例。按照发奖比例发奖

                            //end
                            //发奖，暂时按照全比例发奖
                            user.setCreditScore(user.getCreditScore() + (int) aword);
                            tOrder = gatOrder(user.getId(), (int) aword, user.getCreditScore(), 7, p.getPlayerId());
                            while (true) {
                                double aw = aword;
                                jackpot = tJackpotMapper.selectOne(param);
                                if (jackpot.getPrice().doubleValue() - tOrder.getScore() > 0) {
                                    jackpot.setPrice(BigDecimal.valueOf(jackpot.getPrice().doubleValue() - tOrder.getScore()));
                                    aw = aword;
                                } else {
                                    aw = jackpot.getPrice().doubleValue();
                                    jackpot.setPrice(BigDecimal.valueOf(0));
                                }
                                tOrder = gatOrder(user.getId(), (int) aw, user.getCreditScore(), 7, p.getPlayerId());
                                int success = tJackpotMapper.updateById(jackpot);
                                if (success > 0) {
                                    break;
                                }
                            }
                            tGameUserMapper.updateById(user);
                            tOrderMapper.insert(tOrder);
                        } else {
                            break;
                        }
                    }
                } else if (type.equals("4")) {//集齐奖励
                    Map<String, Object> res = getType(condition.getAwardCondition());
                    String conType = res.get("type").toString();
                    if (conType.equals("0.1")) {

                    }
                    if (conType.equals("0.11")) {

                    }
                    if (conType.equals("15")) {

                    }

                } else {
                    continue;
                }
            }
        } else {
            return;
        }

    }

    private Map<String, Object> getType(String awardCondition) {
        Map<String, Object> map = new HashMap<>();
        String[]  strs=awardCondition.split("-");
        double type = Double.valueOf(strs!=null?strs[0]:"0.0");
        List<Double> valueList = new ArrayList<>();
        if (type == 0.1) {//集齐金牛
            double value = type;
            while (true) {
                valueList.add(value+=value);
                if (value >= 1) {
                    break;
                }
            }
            map.put("data", valueList);
            map.put("type", "0.1");
        } else if (type == 0.11) {//集齐对子
            double value = type;
            while (true) {
                valueList.add(value+=value);
                if (value >= 1) {
                    break;
                }
            }
            map.put("data", valueList);
            map.put("type", "0.11");
        } else if (type >= 1) {//集齐豹子
            valueList.add(type);
            map.put("data", valueList);
            map.put("type",strs[1]);
        }
        return map;
    }

    private double[] getNum(String awardCondition) {
        String[]  strs=awardCondition.split("-");
        double[] nums = new double[strs.length];
        for (int i = 0; i < strs.length; i++) {
            nums[i] = Double.valueOf(strs[i]);
        }
        return nums;
    }

    private TOrder gatOrder(Long id, int i, Integer creditScore, int i1, Long playerId) {
        TOrder tOrder = new TOrder();
        tOrder.setGameUserId(id);
        tOrder.setScore(i);
        tOrder.setCreditScore(creditScore);
        tOrder.setType(i1);//6：奖池次数奖励
        tOrder.setPlayerId(playerId);
        return tOrder;
    }

    /**
     *  获取该游戏玩家的比赛记录，降序排列
     *  遍历游戏记录
     *  如果credit_score小于零跳出，记录次数。目前是该玩家的当前多高连胜记录数。
     *  在判断记录数在符合的条件内。然后给予奖励。
     * @param gamePlayerList
     * @return
     */
    public Integer getLianWin(List<TGamePlayer> gamePlayerList){
        //遍历gamePlayerList 汇总总押注数
        int i = 0;
        for (TGamePlayer gamePlayer :
                gamePlayerList) {
            if (gamePlayer.getCreditScore() > 0) {
                i++;
            }else {
                continue;
            }
        }
        return i;
    }

    public Integer betSum(List<TGamePlayer> gamePlayerList){
        int betSum = 0;
        for (TGamePlayer gamePlayer :
                gamePlayerList) {
            if (gamePlayer.getBet() != null) {
                betSum += gamePlayer.getBet();
            }
        }
        return betSum;
    }



    public static void main(String[] args) {
        String str = "12.34-11.11-10.00";
        String[]  strs=str.split("-");
        List<Double> nums = new ArrayList<>();
        for (String num :
                strs) {
            nums.add(new BigDecimal(Double.valueOf(num)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
        }
        for (Double a :
                nums) {
            System.out.println(a);

        }
    }

    public Date getDate(Integer today) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, today);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
        return zero;
    }

    private  boolean verify(String token){
        TPlayer param = new TPlayer();
        param.setToken(token);
        TPlayer tPlayer = tPlayerMapper.selectOne(param);
        if (tPlayer != null) {
            return true;
        } else {
            return false;
        }

    }


    public Date getEndDate(int validity){
        Integer months = validity;
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        System.out.println(calendar.get(Calendar.MONTH));//今天的日期
        calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)+months);//让日期加1
        System.out.println(calendar.get(Calendar.DATE));//加1之后的日期Top
        return calendar.getTime();
    }

    public String getPlayerToken() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 13);
    }

    /**
     * 获取token
     * @param xlh           手机序列号+用户密码
     * @param playerToken  用户授权码
     * @return 返回token
     */
    public String getToken(String xlh,String playerToken){
        String algorithmName = "MD5";
        Object soure = xlh;//手机序列号
        Object salt = ByteSource.Util.bytes(playerToken); //授权码
        Integer hashIterations = 1024;
        String token = (new SimpleHash(algorithmName,soure,salt,hashIterations)).toString();
        return token;
    }


}
